<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Api;

use App\Middleware\JwtMiddleware;
use App\Model\Information;
use App\Model\Order;
use App\Model\User;
use App\Resource\OrderCollection;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Yansongda\Pay\Pay;

#[Controller]
class OrderController
{
    #[Inject]
    protected RequestInterface $request;

    #[Middleware(JwtMiddleware::class)]
    #[RequestMapping(path: "", methods: "get")]
    public function list()
    {
        /** @var User $user */
        $user = auth()->user();
        $list = $user->order();
        $status = $this->request->input('status');
        if ($status == 1) {
            $list->where('status', 2);
        }

        if ($status == 2) {
            $list->where('status', '!=', 1);
        }

        $list->with(['information' => function ($q) {
            $q->with(['imgs', 'ad', 'cp', 'pc', 'freeRider', 'houseSales', 'jobWanted', 'publicGood', 'recruitment', 'rent', 'solicit']);
        }]);

        $list = $list->paginate((integer)$this->request->input('page_num'));

        $data = [
            'list' => (new OrderCollection($list))->toListApi(),
            'count' => $list->total(),
            'count_page' => $list->lastPage(),
            'page_num' => $list->perPage(),
        ];
        return self::jsonResponse(200, 'success', $data);
    }

    #[Middleware(JwtMiddleware::class)]
    #[RequestMapping(path: "create", methods: "post")]
    /**
     * 创建订单
     * @return false|string
     */
    public function create()
    {
        $informationId = $this->request->input('information_id');
        $information = Information::getById($informationId);
        if (!$information) {
            return self::jsonResponse(404, '数据不存在');
        }

        $order = new Order();
        $order->createNumber();
        $order->setInformation($information);
        $order->user()->associate($information->user_id);
        $order->save();

        return self::jsonResponse(200, 'success', ['id' => $order->id]);
    }

    #[Middleware(JwtMiddleware::class)]
    #[RequestMapping(path: "pay", methods: "post")]
    /**
     * 支付
     * @return false|string
     * @throws \Yansongda\Pay\Exception\ContainerException
     */
    public function pay()
    {
        $id = $this->request->input('id');
        $order = Order::getById($id);
        if (!$order) {
            return self::jsonResponse(404, '订单不存在');
        }

        if ($order->status != 1) {
            return self::jsonResponse(400, '订单状态不正确');
        }

        Pay::config(config('pay.unipay.default'));

        $data = [
            'out_trade_no' => time() . '',
            'description' => '信息置顶-' . ($order->top_days ?? 0) . '天',
            'amount' => [
                'total' => bcmul((string)($order->total ?? 0.00), '100', 2),
                'currency' => 'CNY',
            ],
            'payer' => [
                'openid' => auth()->user()->openid ?? '',
            ]
        ];

        $config = Pay::wechat()->mini($data);
        return self::jsonResponse(200, 'success', $config->toArray());
    }

    #[Middleware(JwtMiddleware::class)]
    #[RequestMapping(path: "cancel", methods: "get")]
    /**
     * 取消订单
     * @return false|string
     */
    public function cancel()
    {
        /** @var User $user */
        $user = auth()->user();
        $id = $this->request->input('id');
        /** @var Order $order */
        $order = $user->order()->where('id', $id)->first();
        if (!$order) {
            return self::jsonResponse(404, '订单不存在');
        }

        if ($order->status != 1) {
            return self::jsonResponse(400, '订单状态不正确,无法取消');
        }
        $order->cancel();
        $order->save();

        return self::jsonResponse(200, 'success');
    }

    #[Middleware(JwtMiddleware::class)]
    #[RequestMapping(path: "delete", methods: "delete")]
    /**
     * 删除
     * @return false|string
     * @throws \Exception
     */
    public function delete()
    {
        /** @var User $user */
        $user = auth()->user();
        $id = $this->request->input('id');
        /** @var Order $order */
        $order = $user->order()->where('id', $id)->first();
        if (!$order) {
            return self::jsonResponse(404, '订单不存在');
        }

        $order->delete();
        return self::jsonResponse(200, 'success');
    }

    public static function jsonResponse(int $status = 1, $message = 'success', $data = null, $headerStatus = 200)
    {
        if (is_array($message)) {
            $data = $message;
            $message = 'success';
        }
        if (empty($data)) {
            $data = new class {
            };
        }

        return json_encode(['status' => $status, 'message' => $message, 'data' => $data]);

//        return response()->json(
//            ['status' => $status, 'message' => $message, 'data' => $data],
//            $headerStatus,
//            [],
//            JSON_UNESCAPED_UNICODE
//        );
    }
}
